package com.freshdirect.src.controller;

import com.freshdirect.src.model.Product;
import com.freshdirect.src.model.Supplier;
import com.freshdirect.src.model.User;
import com.freshdirect.src.service.ProductService;
import com.freshdirect.src.service.UserService;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * Handles requests for the application home page.
 */
@Controller
public class AdminController {
        @Value("${adminname}")
	private String username;
        @Value("${adminpassword}")
	private String password;

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "admin/home", method = RequestMethod.GET)
	public String home( Model model, HttpSession session) {
		if(session.getAttribute("adminName")!=null){
                    return "adminh";
                }
                else{
                    return "redirect:/";
                }
	}
        @RequestMapping(value = "admin/topclients", method = RequestMethod.GET)
	public String topclients(Locale locale, Model model, HttpSession session) {
		
		if(session.getAttribute("adminName")!=null){
                    return "topclients";
                }
                else{
                    return "redirect:/";
                }
	}
        
        @RequestMapping(value="/admin/newproduct", method=RequestMethod.GET)
        public String greetingForm(Model model, HttpSession session) {
            if(session.getAttribute("adminName")!=null){
                ProductService productService= new ProductService();
                List<Product> products = productService.getAll();
                Product product = new Product();
                model.addAttribute("productForm", product);
                List<Supplier> suppliers = productService.getAllSuppliers();
                Map<Integer, String> supplierIDs = new HashMap<Integer, String>();  
                for(int i=0;i<suppliers.size();i++){
                    supplierIDs.put(i+1,suppliers.get(i).getName());
                }
                model.addAttribute("supplierIDs", supplierIDs);  
                model.addAttribute("products",products);
                return "manageproducts";
            }
            else{
                return "redirect:/";
            }
        }
            
        @RequestMapping(value="/admin/newproduct", method=RequestMethod.POST)
        public String greetingSubmit(@Valid @ModelAttribute("productForm") Product product,BindingResult result, Model model, HttpSession session) {
             
            if(session.getAttribute("adminName")!=null){
                if (result.hasErrors()) {
                ProductService productService= new ProductService();
                List<Product> products = productService.getAll();
                model.addAttribute("productForm", product);
                List<Supplier> suppliers = productService.getAllSuppliers();
                Map<Integer, String> supplierIDs = new HashMap<Integer, String>();  
                for(int i=0;i<suppliers.size();i++){
                    supplierIDs.put(i+1,suppliers.get(i).getName());
                }
                model.addAttribute("supplierIDs", supplierIDs);  
                model.addAttribute("products",products);
                 return "manageproducts";
                }
                else{
                ProductService productService= new ProductService();
            
                int id = productService.saveProduct(product);
            
                //model.addAttribute("messagebad", "Product created succesfully!");
                return "redirect:/product/"+ id;
                }
            }
            else{
                return "redirect:/";
            }
        }
        
        @RequestMapping(value="/admin/viewusers", method=RequestMethod.GET)
        public String viewUsers(Model model, HttpSession session) {
            
            if(session.getAttribute("adminName")!=null){
                UserService us = new UserService();
                List<User> users = us.getUsers();
                model.addAttribute("users", users);
                return "viewusers";
            }
            else{
                return "redirect:/";
            }
        }
        
        @RequestMapping(value="/admin/6degrees", method=RequestMethod.GET)
        public String degrees(@RequestParam Map<String,String> params, Model model, HttpSession session) {
            
            if(session.getAttribute("adminName")!=null){
                if(params.get("supplier1") != null){
                    ProductService ps = new ProductService();
                    int degree = ps.findDegreeOfSeparation(Integer.parseInt(params.get("supplier1")),Integer.parseInt(params.get("supplier2")));
                    List<Supplier> suppliers = ps.getAllSuppliers();
                    model.addAttribute("degree",degree);
                    model.addAttribute("suppliers", suppliers);
                    return "6degrees";
                }
                else{
                    ProductService ps = new ProductService();
                    List<Supplier> suppliers = ps.getAllSuppliers();
                    model.addAttribute("suppliers", suppliers);
                    return "6degrees";
                }
            }
            else{
                return "redirect:/";
            }
        }
        
        @RequestMapping(value="/admin/signin", method=RequestMethod.GET)
        public String signIn() {
           
           return "adminsign";           
        }
        
        @RequestMapping(value="/admin/signin", method=RequestMethod.POST)
        public String signIn(HttpServletRequest request, Model model, HttpSession session) {
            
            String userName=request.getParameter("username");
            String passWord=request.getParameter("password");
            System.out.println(userName +"  "+ passWord);
            System.out.println(this.username +"  "+ this.password);
            if(userName.equals(this.username) && passWord.equals(this.password)){
               request.getSession().invalidate();
               request.getSession().setAttribute("adminName",userName);
               return "redirect:/admin/home";   
            }else{
                return "redirect:/admin/signin";
            }            
        }
        
        @RequestMapping(value="/admin/signout", method=RequestMethod.GET)
        public String processLogout(HttpServletRequest request,HttpSession session){
            if(session.getAttribute("adminName")!=null){
             request.getSession().invalidate();
             return "redirect:/admin/signin";   
            }
            else{
                return "redirect:/";
            }
        }
        
        

}